#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem> //c++17
#include <fstream>
#include <sstream>
#include <cstdio>
#include <memory>
#include <unistd.h>
#include "Mutex.hpp"

using namespace MutexModule;

namespace LogModule
{
    const std::string sep = "\r\n";
    const std::string defaultpath = "./log";
    const std::string defaultfilename = "my.log";
    class LogStrategy
    {
    public:
        virtual void syncLog(std::string &message) = 0;
    };

    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        void syncLog(std::string &message) override
        {
            LockGuard guard(_mutex);
            std::cerr << message << std::endl;
        }

    private:
        Mutex _mutex;
    };

    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &filename = defaultfilename)
            : _path(path), _filename(filename)
        {
            if (std::filesystem::exists(_path))
                return;
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        void syncLog(std::string &message) override
        {
            LockGuard guard(_mutex);
            std::string name = _path + (_path.back() == '/' ? "" : "/") + _filename;
            std::ofstream out(name, std::ios::app);
            if (out.is_open())
                return;
            out << message << sep;
            out.close();
        }

    private:
        std::string _path;
        std::string _filename;
        Mutex _mutex;
    };

    // 奥特曼等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATEL
    };

    // 甜心超人
    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        void EnableConsoleLogStrategy()
        {
            _strategy = std::make_unique<ConsoleLogStrategy>();
        }

        void EnableFileLogStrategy()
        {
            _strategy = std::make_unique<FileLogStrategy>();
        }

        // 内部奥特曼
        class LogMessage
        {
        private:
            std::string GetTimeStamp()
            {
                time_t tm = time(nullptr);
                struct tm ctime;
                // 可重入，线程安全的
                localtime_r(&tm, &ctime);
                // std::stringstream ss;
                // ss << ctime.tm_year + 1900
                //    << ctime.tm_mon
                //    << ctime.tm_mday
                //    << ctime.tm_hour
                //    << ctime.tm_min
                //    << ctime.tm_sec;
                // return ss.str();

                char timebuffer[64];
                snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
                         ctime.tm_year + 1900,
                         ctime.tm_mon + 1,
                         ctime.tm_mday,
                         ctime.tm_hour,
                         ctime.tm_min,
                         ctime.tm_sec);
                return timebuffer;
            }

            const std::string LevelToStr(LogLevel &level)
            {
                switch (level)
                {
                case LogLevel::DEBUG:
                    return "DEBUG";
                case LogLevel::INFO:
                    return "INFO";
                case LogLevel::WARNING:
                    return "WARNING";
                case LogLevel::ERROR:
                    return "ERROR";
                case LogLevel::FATEL:
                    return "FATEL";
                default:
                    return "UNKNOWN";
                }
            }

        public:
            // 初始化奥特曼
            LogMessage(LogLevel &level,
                       const std::string &srcname,
                       size_t lineno,
                       Logger &logger)
                : _current_time(GetTimeStamp()), _level(level), _pid(getpid()), _srcname(srcname), _lineno(lineno), _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _current_time << "] "
                   << "[" << LevelToStr(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _srcname << "] "
                   << "[" << _lineno << "] "
                   << "- ";
                _loginfo += ss.str();
            }

            template <class T>
            LogMessage &operator<<(const T &message)
            {
                std::stringstream ss;
                ss << message;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                _logger._strategy->syncLog(_loginfo);
            }

        private:
            std::string _current_time; // 奥特曼vs雷德王所需要的时间
            LogLevel _level;           // 奥特曼等级
            pid_t _pid;                // 关卡进程
            std::string _srcname;      // 奥特曼名字
            size_t _lineno;            // 几个奥特曼
            std::string _loginfo;      // 奥特曼说了什么
            Logger &_logger;           // 释放奥特曼
        };

        LogMessage operator()(LogLevel type,
                              const std::string &name,
                              size_t lineno)
        {
            return LogMessage(type, name, lineno, *this);
        }

    private:
        std::unique_ptr<LogStrategy> _strategy; // 奥特曼策略
    };
    // 开心超人
    Logger logger;

    // 使用宏，简化用户操作
#define LOG(level) logger(level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG_STRATEGY() logger.EnableConsoleLogStrategy()
#define ENABLE_FILE_LOG_STRATEGY() logger.EnableFileLogStrategy()
}